<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/9
 * Time: 14:14
 */

/**
 * @param $code
 * @param $message
 * @param null $info
 */
function json_exit ($code, $message, $info = NULL)
{
    $rt = array(
        'code' => $code,
        'msg' => $message
    );

    if ($info !== NULL)
    {
        $rt['info'] = $info;
    }

    echo json_encode($rt);
    exit();
}

/**
 * 自定义的错误处理函数
 * @param $errno
 * @param $errstr
 * @param $errfile
 * @param $errline
 */
function my_error_handler($errno, $errstr, $errfile, $errline)
{
    if ($errno === E_USER_ERROR)
    {
        list($errmsg, $errcode) = explode('|', $errstr, 2);
        if (!$errcode)
        {
            $errcode = 500;
        }
        json_exit($errcode, $errmsg);
    }
    else
    {
        _error_handler($errno, $errstr, $errfile, $errline);
    }
}

/**
 * 返回错误
 * @param $errcode
 * @param $errmsg
 */
function error($errcode, $errmsg)
{
    trigger_error("$errmsg|$errcode", E_USER_ERROR);
}

/**
 * 简单记录日志方便调试
 * @param $message
 */
function easyLog($message)
{
    $logFile = APPPATH. 'logs/easyLog_' . date('Y-m-d') . '.log';

    $message = '[' . date('Y-m-d H:i:s') . ']  ' . $message . PHP_EOL . PHP_EOL;

    file_put_contents($logFile, $message, FILE_APPEND);

    if (posix_getuid() === 0)
    {
        chown($logFile, 'nobody');
        chgrp($logFile, 'nobody');
    }
}




/**
 * curl封装方法
 * @param $url
 * @param $params
 * @param string $method
 * @param int $timeout
 * @return mixed
 */
function httpCurl($url, $params, $method='GET', $timeout = 10)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);

    $params = http_build_query($params);

    if ($method == 'GET')
    {
        if (parse_url($url, PHP_URL_QUERY))
        {
            $url = rtrim($url, '&');
            $url .= '&' . $params;
        }
        else
        {
            $url = rtrim($url, '?');
            $url .= '?' . $params;
        }
    }

    curl_setopt($ch, CURLOPT_URL, $url);

    if ($method == 'POST')
    {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
    }

    $res = curl_exec($ch);

    curl_close($ch);

    return $res;
}

/**
 * @param $params
 * 必填参数验证
 */
function mustParams($params)
{
    foreach($params as $key=>$value){
        if(empty($value)){
            json_exit(10004,'缺少参数');
        }
    }
}

  // 单位自动转换函数
    function getRealSize($size){
        $kb = 1024;         
        $mb = 1024 * $kb;   
        $gb = 1024 * $mb;   
        $tb = 1024 * $gb;  
         
        if($size < $kb)
        {
            return $size." B";
        }
        else if($size < $mb)
        {
            return round($size/$kb,2)." KB";
        }
        else if($size < $gb)
        {
            return round($size/$mb,2)." MB";
        }
        else if($size < $tb)
        {
            return round($size/$gb,2)." GB";
        }
        else
        {
            return round($size/$tb,2)." TB";
        }
    }
	 // 单位自动转换函数从MB开始换算
    function getSize($size){
        $mb = 1024;         
        $gb = 1024 * $mb;   
        $tb = 1024 * $gb;   
         
        if($size < $mb)
        {
            return $size." MB";
        }
        else if($size < $gb)
        {
            return round($size/$mb,2)." GB";
        }
        else if($size < $tb)
        {
            return round($size/$gb,2)." TB";
        }
      
    }

    /**
     * 获取扩展名
     */

    function getExt($str){

        $arr = explode('.', trim($str));
     
        return array_pop($arr);
    }
    /**
    *根据后缀名获取图片地址
    */
    function getImg($ext){
        switch ($ext) {
            case 'jpg':
               return  "/file_service/resource/img/mime_img32.png";
                break;
            case 'png':
                 return  "/file_service/resource/img/mime_img32.png";
                break;
            case 'zip':
                return  "/file_service/resource/img/mime_compress32.png";
                break;
                case 'txt':
                return  "/file_service/resource/img/mime_txt32.png";
                break;
				case 'gif':
                return  "/file_service/resource/img/mime_img32.png";
                break;
            default:
               return  "/file_service/resource/img/file.png";
                break;
        }
    }


    /**
    *@path文件存储路径
    *@newname文件新名称
    *@oldname文件旧名称
    */
    function fileRename($path,$newname,$oldname){
        $oldname = $path.$oldname;
        $newname = $path.$newname;
        if(!file_exists($oldname)||file_exists($newname)){
            json_exit('20003',"目标文件存在或源文件不存在");
        }else{
            $h =rename($oldname, $newname);
        }      
        if($h){
            return true;
        }else{
            return false;
        }
    }

/**
*带宽计算
*/
function changeWide($size) {
        $size *= 8;
        if($size > 1024 * 1024 * 1024) {
                $size = round($size / 1073741824 * 100) / 100 . ' Gbps';
        } elseif($size > 1024 * 1024) {
                $size = round($size / 1048576 * 100) / 100 . ' Mbps';
        } elseif($size > 1024) {
                $size = round($size / 1024 * 100) / 100 . ' Kbps';
        } else {
                $size = $size . ' Bbps';
        }
        return $size;
}

/**
*每天下载5分钟日志
*/
function dayLog($mercode,$downLoadtimes,$downLoadsize,$bandWide){
    $date = date("Ymd");
    $time = date('Y-m-d H:i:s');
    $logpath = '/data/log/file_service/'.$date.'/';
    if(!file_exists($logpath)){
        mkdir($logpath);
    }
    $log = "date:".$date."|mercode:".$mercode."|usetime:".$downLoadtimes."|size:".$downLoadsize."|bandWide;".$bandWide."|downloadtime:". $time;
    file_put_contents($logpath.date("Y-m-d").'dayLoad'.$mercode.'.txt',$log. "\r\n",FILE_APPEND);
}
/**
*通用下载日志
*@$vid
*@mercode商户号
*$muid
*download下载文件名
*/
function commonLog($mercode,$muid,$download,$datetime){
    static $id;
    $date = date("Ymd");
    $logpath = '/data/log/file_service/'.$date.'/';
    if(!file_exists($logpath)){
        mkdir($logpath);
    }
    $id++;
    $log = "id:".$id."|mercode:".$mercode."|muid:".$muid."|flow:".$download."|datetime:".$datetime;
    file_put_contents($logpath.date("Y-m-d")."downLoad$mercode.txt",$log. "\r\n",FILE_APPEND);
}
/**
*5分钟带宽流量
*@$total下载总流量
*@$starttime开始下载时间
*@$endtime结束下载时间
*/
 function bandWide($total,$start,$end)
 {
    //$x当前时间
    //$s为开始时间
    //start/end下开始时间和结束时间   
    $t = $total;//总流量
    $x = getMicrotime();//当前时间
    $s = $start;
    $e = $end;  
	
    $r = round($t/($end-$start));//每秒下载流量
	//echo $r;die;
    $m = $s/300;//一天内每5分钟一片后的序号

    $s=$m*300;
    $m = round($m);
    while ( $s< $e) {
        if($s<=$x&&$s+300>=$e){			
            $d[$m]=$r;
            break;
        }else if($s<=$x){
            $d[$m]=(300+$s-$x)*$r;
        }else if($x>=$e){
            $d[$m]=(300+$e-$s)*$r;
        }else{
            $d[$m]=300*$r;
        }
        $m++;
        $x+=300;
    }
    return $d[$m];
 }
 /**
 *获取当前时间精确到毫秒
 */
 function getMicrotime(){

   list($usec, $sec) = explode(" ", microtime());
	
	$sec = ((float)$usec + (float)$sec);
   return round($sec,2);

}
/**
*每天总流量统计的json文件便于生成图表
*@$daycount每天的总流量
*@$date日期$date=date('Ymd');
*/
function mouthlog($daycount,$date,$mercode){
	
	$logpath = '/data/log/file_service/';
     $logfile=$logpath.date("Y-m").'_'.$mercode.'.json';
    
    if(file_exists($logfile)){
         $jsondata = file_get_contents($logfile);//获取当前已存在的json文件内的数据  
          $arr = json_decode($jsondata,true);//转换成数组
		 
          $arr[$date]=$daycount;
		  
    }else{
          $arr[$date]=$daycount;
        
    }
		$redis= getHandle();
		$key = $mercode.'_'.$date;
		$redis->set($key,$arr[$date]);
		
		
      file_put_contents($logfile,json_encode($arr));//获取当前已存在的json文件内的数据  

} 

/**
*下载流量json文件
*@hourcount 每小时下载总流量
*@$hour当前小时数示例$hour=date('H');
*@mercode商户号
*/
 function  hourFlow($flow,$time,$mercode){
    $count = array();  
	$flow = changeflow($flow);
    //static $total=0;
	$tot=0;
    $date = date('Ymd');
   // $utime = isset($_SESSION["time_$mercode"]) ? $_SESSION["time_$mercode"] : '';
   // if($utime !=$time || !isset($_SESSION["time_$mercode"])){
      //$hour = $_SESSION["time_".$mercode] = $time; 
    //  $total=0;
    //}
   // $total+=$flow;//每个小时总流量统计 
	$nowtime=date('YmdHis');
	$hour = date('YmdH');
	$redis=getHandle();
	$redis->hset($hour.$mercode, $nowtime, $flow);
	$count = $redis->hgetall($hour.$mercode);
	foreach($count as $v){
		$tot+=$v;
	}
	$redis->hset($date.$mercode, $hour, $tot);
	$total = $redis->hget($date.$mercode,$hour);
     //$count[$date][$time]=$total;
	

    flowlog($total,$time,$mercode);
	$redis->close();
}
/**
*下载流量json文件
*@hourcount 每小时下载总流量
*@$hour当前小时数示例$hour=date('H');
*@mercode商户号
*/
function flowlog($hourcount,$hour,$mercode){
	
    $logpath = "/data/log/file_service/";
    if(!file_exists($logpath)){
        mkdir($logpath);
    }
	$logfile= $logpath.date("Y-m-d").'_'.$mercode.'.json';
	
    if(file_exists($logfile)){
        $jsondata=file_get_contents($logfile);//获取当前已存在的json文件内的数据  
        $arr = json_decode($jsondata,true);//转换成数组
        $arr[$hour]= $hourcount;//添加进当前一个小时的流量
    }else{
        $arr[$hour]= $hourcount;//添加进当前一个小时的流量
      
    }

      file_put_contents($logfile,json_encode($arr));
}
/**
*每天流量统计读取每天生成的j每小时流量son文件进行统计
*@date日期示例$date=date("Y-m-d");
*/
 function dayCount($date,$mercode){
	 $count = 0;
	$logpath="/data/log/file_service/";
	$logfile=$logpath.$date.'_'.$mercode.'.json';
    $arr=file_get_contents($logfile);
	
    $res=json_decode($arr,true);
     
    foreach ($res as $val) {
        $count+=$val;
    }
    return  $count;
}
/**
*流量单位换算统一换成MB便于图表展示
*/  
function changeflow($size){
	$mb=1024*1024;
     return round($size / $mb,2) ;
}

function getHandle(){

	$_redis=NULL;
	  $ci = & get_instance();
        $ci->config->load('redis', TRUE);
        if ($_redis === NULL)
        {
            $_redis = new Redis();
            $_redis->connect($ci->config->item('host', 'redis'), $ci->config->item('port', 'redis'));
        }

        return $_redis;
}


 /** 下载
     * @param String  $file   要下载的文件路径
     * @param String  $name   文件名称,为空则与下载的文件名称一样
     * @param boolean $reload 是否开启断点续传
     */
    function download($file, $name='', $reload=false){
        $fp = @fopen($file, 'rb');
        if($fp){
            if($name==''){
                $name = basename($file);
            }
            $header_array = get_headers($file, true);
            //var_dump($header_array);die;
            // 下载本地文件，获取文件大小
            if (!$header_array) {
                $file_size = filesize($file);
            } else {
                $file_size = $header_array['Content-Length'];
            }
            $ranges = getRange($file_size);
            $ua = $_SERVER["HTTP_USER_AGENT"];//判断是什么类型浏览器
            header('cache-control:public');
            header('content-type:application/octet-stream');    

            $encoded_filename = urlencode($name);
            $encoded_filename = str_replace("+", "%20", $encoded_filename);

            //解决下载文件名乱码
            if (preg_match("/MSIE/", $ua) ||  preg_match("/Trident/", $ua) ){               
                header('Content-Disposition: attachment; filename="' .$encoded_filename . '"');
            } else if (preg_match("/Firefox/", $ua)) {
                header('Content-Disposition: attachment; filename*="utf8\'\'' . $name . '"');
            }else if (preg_match("/Chrome/", $ua)) {
                header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
            } else {
                header('Content-Disposition: attachment; filename="' . $name . '"');
            }
            //header('Content-Disposition: attachment; filename="' . $name . '"');

            if($reload && $ranges!=null){ // 使用续传
                header('HTTP/1.1 206 Partial Content');
                header('Accept-Ranges:bytes');

                // 剩余长度
                header(sprintf('content-length:%u',$ranges['end']-$ranges['start']));

                // range信息
                header(sprintf('content-range:bytes %s-%s/%s', $ranges['start'], $ranges['end'], $file_size));
                //file_put_contents('test.log',sprintf('content-length:%u',$ranges['end']-$ranges['start']),FILE_APPEND);
                // fp指针跳到断点位置
                fseek($fp, sprintf('%u', $ranges['start']));
            }else{
               
                header('HTTP/1.1 200 OK');
                header('content-length:'.$file_size);
            }

            while(!feof($fp)){
                //echo fread($fp, round($this->_speed*1024,0));
                //echo fread($fp, $file_size);
                echo fread($fp, 4096);
                ob_flush();
            }

            ($fp!=null) && fclose($fp);
        }else{
            return '';
        }
    }
	
	  /** 设置下载速度
     * @param int $speed
     */
   function setSpeed($speed){
        if(is_numeric($speed) && $speed>16 && $speed<4096){
            $this->_speed = $speed;
        }
    }
	    /** 获取header range信息
     * @param  int   $file_size 文件大小
     * @return Array
     */
   function getRange($file_size){
        //file_put_contents('range.log', json_encode($_SERVER), FILE_APPEND);
        if(isset($_SERVER['HTTP_RANGE']) && !empty($_SERVER['HTTP_RANGE'])){
            $range = $_SERVER['HTTP_RANGE'];
            $range = preg_replace('/[\s|,].*/', '', $range);
            $range = explode('-', substr($range, 6));
            if(count($range)<2){
                $range[1] = $file_size;
            }
            $range = array_combine(array('start','end'), $range);
            if(empty($range['start'])){
                $range['start'] = 0;
            }
            if(empty($range['end'])){
                $range['end'] = $file_size;
            }
            return $range;
        }
        return null;
    }
	//获取当每小时下载流量
	function dayFlow($mercode){
				$thedaylog = 'file_service_access.log';//当天下载日志
				$logpath = "/data/log/file_service/";
				$logfile= $logpath.date("Y-m-d").'_'.$mercode.'.json';
				 if(!file_exists($logpath)){
					mkdir($logpath);
				}		
			
				$h=date('H');		
				$arr=array();
				for($i=0;$i<=$h;$i++){				
					$time = date('d/M/Y:'.$i.':');
					
					$command="cat /data/log/nginx/$thedaylog | grep $time | grep uploads |grep merCode=$mercode |awk -F'[][]' '{print  $24 }' |awk '{sum+=$1}END{print sum}'";
					exec($command,$ret);
					if($ret){
						$arr["$i"]=round($ret[$i]/(1024*1024),2);
					}
					$daycount += $ret[$i];	//每天下载总流量									
														
				}			
				file_put_contents($logfile, json_encode( $arr ));
				return $daycount;
				
	}
	//统计到今天为止的每天的流量
	function dayFlowTotal($mercode){
				$date=date('Ymd');
				$d=date('d');
				$arr=array();
				$logpath = "/data/log/file_service/";
				$filelog = 'file_service_access.log-'.$date;//前一天下载日志
				 if(!file_exists($logpath)){
					mkdir($logpath);
				}
				for($j=0;$j<$d;$j++){
					
				}
				
				for($i=0;$i<=24;$i++){
					$time = date('d/M/Y:'.$i);
					$data= system("/opt/web/file_service/getdata.sh {$time} {$filelog} {$mercode}",$ret);
					$arr["$i"]=round($data/(1024*1024),2);
					$daycount += $data;	//每天下载总流量
				}
				return $daycount;
	}
		 function getLogin(){
			$c=array('user','RequestCdn','Content');
			$m=array('login','file',' test','download','do_upload','upload');
			$getc=$_GET['c'];
			$getm=$_GET['m'];
			if(	empty($_GET)){
				hrefurl();
			}else if(!in_array($getc,$c) && !in_array($getm,$m)){
				 hrefurl();
			}else if($_COOKIE['mercode']==''){
				 hrefurl();
			}
		}
		 function hrefurl(){
				$url = "?c=user&m=login";  
				echo "<script language='javascript' type='text/javascript'>";    
                echo "window.location.href='$url'";    
                echo "</script>"; 
				exit;
		}

